from wtforms import StringField, IntegerField
from wtforms.validators import DataRequired, Length, Email, Regexp, ValidationError

from app.models.apis import Apis, ApisScene, Scene, Config
from app.validators.base import BaseForm as Form


class ApisForm(Form):
    api_name = StringField(
        validators=[DataRequired(message='不允许为空'), Length(min=1, max=5000)])  # 接口名称唯一，后续要个参数表，根据接口名称传递参数
    request_method = StringField(validators=[DataRequired(message='不允许为空'), Length(min=1, max=5000)], default="post")
    path = StringField(validators=[DataRequired(message='不允许为空'), Length(min=1, max=5000)])
    headers = StringField()
    parameter = StringField()
    asserts_expression = StringField()

    def validate_api_name(self, value):
        if Apis.query.filter_by(api_name=value.data).first():
            raise ValidationError(message='该接口已被记录，无需重复记录')


class SceneForm(Form):
    scene_name = StringField(validators=[DataRequired(message='不允许为空')])
    api_name_list = StringField(validators=[DataRequired(message='不允许为空')])
    def validate_scene_name(self, value):
        if Scene.query.filter_by(scene_name=value.data).first():
            raise ValidationError(message='该场景已被记录，无需重复记录')

class ApisSceneForm(Form):
    scene_name = StringField(validators=[DataRequired(message='不允许为空')])
    request_parameter=StringField()
    is_depend=IntegerField() #是否需要依赖，依赖 0是不需要 1是依赖请求参数 2是依赖响应参数
    depend_api_name=StringField() #被依赖的接口名称
    depend_field=StringField()#需要依赖的字段
    depend_expression=StringField() #提取依赖字段的表达式
    asserts_expression = StringField()

class SceneScriptForm(Form):
    scene_name = StringField(validators=[DataRequired(message='不允许为空')])
    script_data=StringField(validators=[DataRequired(message='脚本参数不能为空')])
    def validate_scene_name(self, value):
        scene_id=Scene.query.filter_by(scene_name=value.data).first().id
        a=ApisScene.query.filter_by(scene_id=scene_id).all()
        #只有有一个为空，该场景脚本就未被设置完成
        b = 0
        for i in a:
            if i.is_depend==None:
                b+=1
        if b==0:
            raise ValidationError(message='该场景已被记录，无需重复记录')

class ConfigForm(Form):
    ip = StringField(validators=[DataRequired(message='不允许为空')])
    ip_name=StringField(validators=[DataRequired(message='不允许为空')])

# class ConfigUseForm(ConfigForm):
#      ip_name= StringField(validators=[DataRequired(message='环境名称不允许为空')])
#      def validate_ip_name(self, value):
#         if not Config.query.filter_by(ip_name=value):
#             raise ValidationError(message='未查询到该测试环境，检查环境名称输入是否正确')
